import React, { Component } from 'react';
import {
    View, StyleSheet, Text, TouchableOpacity, Modal,
    Image, AppState, ScrollView, Animated, Dimensions
} from 'react-native';

import { connect } from 'react-redux';
import Toast from 'react-native-easy-toast';

import NccButton from '../components/Button';
import { TABBAR_LABEL, ROUTERMAP, Global, API_MAP, TOAST_MESSAGE } from '../util/constants';
import { request } from '../util';
import * as balanceAction from '../actions/balance';
import * as exchangeBalanceAction from '../actions/exchangeBalance';
import { subscribeCoinxpMarket, closeCoinxpMarket, emitLogoutTrade, subscribeCoinxpUserOrder } from '../util/socket';
import { scaleSize, scaleFontSize } from '../util/size';
import CommonTitleBar from '../components/CommonTitleBar';
// import EntrustItem from '../components/EntrustItem';
import EntrustList from '../components/EntrustList';
import CoinTypeSelect from '../components/CoinTypeSelect';
import TransactionLeftArea from '../components/TransactionLeftArea';
import icons from '../util/icons';
import { utilGetAvailableByCoinType } from '../util/balanceUtil';
import { utilUserIsLogin } from '../util/userUtil';
import { INavigation, IReduxBalanceInfo, IReduxUserInfo, IEntrustItem, IReduxMarketInfo, IReduxRecentTransactionArray, IReduxLastPrice } from '../interface';
import { utilValidCheck } from '../util/validCheck';
import { utilTransferInputValue } from '../util/util';
import { utilGetLastPrice, utilGetAmountToByCoinType } from '../util/marketUtil';
import { insertLastPrice, IFuncInsertLastPrice } from '../actions/lastPrice';

const { width: deviceWidth, height: deviceHeight } = Dimensions.get('window');

const DEFAULT_ORDER_TOP = [
    {price: 0, amount: 0},
    {price: 0, amount: 0},
    {price: 0, amount: 0},
    {price: 0, amount: 0},
    {price: 0, amount: 0},
    {price: 0, amount: 0},
    {price: 0, amount: 0},
    {price: 0, amount: 0},
    {price: 0, amount: 0},
];

interface IState {
    username: string,
    nowTab: string,  // 当前选择状态， 买入 buy 或者 卖出 sell
    topOrderData: any, // 行情数据
    targetCoinType: string,  // 目标选项，对应 CONINOPTIONS
    payCoinType: string,  // 支付选项，对应 CONINOPTIONS
    currentPriceCNY: number, // 当前价值人民币
    buyPrice: string,  // 买入限价
    sellPrice: string,  // 卖出限价
    buyPriceAmountTo: number,  // 买入限价 约等于人民币
    sellPriceAmountTo: number,  // 卖出限价 约等于人民币
    buyTotal: number,  // 买入的交易额
    sellTotal: number,  // 卖出的交易额
    buyAmount: string,  // 买入数量
    sellAmount: string,  // 卖出数量
    coinType: string,
    available: {
        [propName: string]: number
    },  // 可用， {coinType: amount}
    transactionLoading: boolean,
    availableSell: number,  // 卖出可用
    availableBuy: number, // 买入可用
    orderData: Array<IEntrustItem>,  // 最近委托数据
    orderDataFilter: boolean,
    sellSliderValue: number,
    buySliderValue: number,
    currentTrasactionTab: string,
    currentOptionTab: string,
    visiable: 'flex' | 'none',
    modalVisible: boolean,
    lastPrice: number,
    navProps: string,
    [propName: string]: any
}

interface IProps {
    // updateBalanceInfo: Function,
    navigation: INavigation,
    balance: IReduxBalanceInfo,
    user: IReduxUserInfo,
    marketInfo: IReduxMarketInfo,
    recentTransaction: IReduxRecentTransactionArray,
    insertLastPrice: IFuncInsertLastPrice,
    updateExchangeBalanceInfo: exchangeBalanceAction.IFuncUpdateExchangeBalanceInfo,
}

class Transaction extends Component<IProps, IState> {
    isLogin:boolean;
    constructor(props) {
        super(props);
        // this.state
        this.state = {
            username: '',
            nowTab: 'buy',
            topOrderData: {},
            targetCoinType: 'ETH',
            payCoinType: 'BTC',
            currentPriceCNY: 6.83,
            buyPrice: '',
            sellPrice: '',
            buyPriceAmountTo: 0,
            sellPriceAmountTo: 0,
            buyTotal: 0,
            sellTotal: 0,
            buyAmount: '',
            sellAmount: '',
            available: { ETH: 0, BTC: 0 },
            transactionLoading: true,
            availableSell: 0,
            availableBuy: 0,
            orderData: [],
            orderDataFilter: false,
            currentAppState: AppState.currentState,
            // navState: this.props.navigation.state,
            buySliderValue: 0,
            sellSliderValue: 0,
            currentTrasactionTab: 'now',
            currentOptionTab: 'buy',
            isVisible: true,
            fadeAnim: new Animated.Value(-deviceWidth),
            visiable: 'none',
            modalVisible: false,
            coinType: 'ETH/BTC',
            lastPrice: 0,
            navProps: '', // componentWillReceiveProps 传进来的 navigation.state.param 判断 
        }
        this.isLogin = false;
    }

    static navigationOptions = {
        tabBarLabel: TABBAR_LABEL.trasaction,
        tabBarIcon: ({ focused, tintColor }) => {
            if (focused) {
                return (
                    <Image source={icons.tabExchangeO} style={Global.tabIconStyles} />
                );
            }
            return (
                <Image source={icons.tabExchange} style={Global.tabIconStyles} />
            );
        },
    };

    componentWillReceiveProps (nextProps) {
        // navProps  与 新进来的 props 比较
        let {navProps: _navProps} = this.state;
        try {
            const {coinType, opStatus} = nextProps.navigation.state.params;
            const navProps = coinType + opStatus;
            if (_navProps != navProps) {
                this.setState({coinType, nowTab: opStatus, navProps});
            }
        } catch (e) {
        }

        let {userNameChain = null} = nextProps.user; 
        let userNameChainProps = this.props.user.userNameChain;

        if (userNameChain && userNameChainProps) {
            this.isLogin = true;
            subscribeCoinxpUserOrder({userNameChain});
        }

        if (!userNameChain && !userNameChainProps) {
            if (this.isLogin) {
                // this.setState({orderData: []});
                emitLogoutTrade();
                this.resetState();
                this.isLogin = false;
            }
        }
    }

    componentDidMount() {
        console.log('Trasaction did mount....');
        // AppState.addEventListener('change', this.handleAppStateChange);
        const { navigation } = this.props;
        const coinType = navigation.getParam('coinType', 'ETH/BTC');
        const opStatus = navigation.getParam('opStatus', 'buy');
        if (coinType) {
            this.setState({ coinType: coinType, nowTab: opStatus });
        }

        const user = this.props.user;

        subscribeCoinxpMarket(user, (_, type, data) => {
            // console.log('subscribeCoinxpMarket......', data);
            if (type === 'userTrades') {
                if (this.isLogin) {
                    this.setState({orderData: data});
                }
            }

            if (type === 'coinxpMarketInfo') {
                this.transLastPrice(data);
                this.setState({topOrderData: data});
            }
        });

        this.getLastPrice();
    }

    componentWillUnmount() {

    }

    componentWillUpdate(nextProps, nextState) {
        // console.log('nextState.navState', nextState.navState);
    }

    resetState = () => {
        this.setState({
            buyPrice: '', buyAmount: '', buyPriceAmountTo: 0, buyTotal: 0, buySliderValue: 0,
            sellPrice: '', sellAmount: '', sellPriceAmountTo: 0, sellTotal: 0, sellSliderValue: 0,
            orderData: [],
        })
    }

    transLastPrice = (data) => {
        let {coinType} = this.state;
        let _data = data[coinType];
        if (!_data) {
            return;
        }
        let {lastPrice = null}: {lastPrice: (IReduxLastPrice | null)} = _data;
        lastPrice = {
            amount: Math.random() * 10,
            price: 0.04,
            timestamp: Math.floor((Date.now() / 1000)).toString(),
        }
        if (lastPrice) {
            this.props.insertLastPrice(coinType, lastPrice);
            let price = lastPrice.price;
            this.setState({recommendBuyPrice: price, recommendSellPrice: price, lastPrice: price});
        }
    }

    toast = (content: string) => {
        this.refs.toast.show(content);
    }

    handleCancel = (orderId) => {
        if (orderId) {
            request(API_MAP.cancel, {
                method: 'POST',
                data: {
                    orderId: orderId,
                }
            }, false, (err, res) => {
                if (res.retCode == '00') {
                    this.reloadUserBalanceData();
                    return this.toast(TOAST_MESSAGE.SUCCESS);
                }
                return this.toast(TOAST_MESSAGE.FAILED);
            })
        }
    }

    getLastPrice = () => {
        request(API_MAP.lastPrice, {
            method: 'get'
        }, false, (err, res) => {
            if (res.retCode == '00') {
                console.log('getLastPrice......', res);
                let data = res.data;
                if (data.lastPrice) {
                    let p = data.lastPrice.toString();
                    this.onChangeBuyPrice(p);
                    this.onChangeSellPrice(p);
                    this.setState({recommendBuyPrice: p, recommendSellPrice: p, lastPrice: p});
                }
            }
        })
    }

    isValidOfPriceRange = (type: 'sell' | 'buy') : boolean => {
        let { recommendBuyPrice, recommendSellPrice, buyPrice, sellPrice } = this.state;
        console.log('priceRange..', recommendBuyPrice, recommendSellPrice, buyPrice, sellPrice);
        if (recommendBuyPrice <= 0 || recommendSellPrice <= 0) {
            return true;
        }
        if (type === 'buy') {
            if (Number(buyPrice) < Number(recommendBuyPrice) * 0.8 || Number(buyPrice) > recommendBuyPrice * 1.2) {
                return false;
            } else {
                return true;
            }

        } else if (type === 'sell') {
            if (Number(sellPrice) < recommendSellPrice * 0.8 || Number(sellPrice) > recommendSellPrice * 1.2) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    isValidOfBuyData = () => {
        const {buyPrice, buyAmount} = this.state;
        if (!this.isValidOfPriceRange('buy')) {
            this.toast(TOAST_MESSAGE.PRICE_RANGE_INVALID);
            return false;
        }
        if (Number(buyAmount) > 0 && Number(buyPrice) > 0) {
            return true;
        }
        return false;
    }

    isValidOfSellData = () => {
        const {sellPrice, sellAmount} = this.state;
        if (!this.isValidOfPriceRange('sell')) {
            this.toast(TOAST_MESSAGE.PRICE_RANGE_INVALID);
            return false;
        }
        if (Number(sellPrice) > 0 && Number(sellAmount) > 0) {
            return true;
        }
        return false;
    }

    handleBuy = () => {

        const {buyAmount, buyPrice, coinType, payCoinType } = this.state;
        console.log('buyAmount, buyPrice, coinType, payCoinType', buyAmount, buyPrice, coinType, payCoinType);
        // if (!utilValidCheck(buyPrice, 'price')) {
        //     return this.toast(TOAST_MESSAGE.PRICE_INVALID);
        // }
        // if (!utilValidCheck(buyAmount, 'amount')) {
        //     return this.toast(TOAST_MESSAGE.AMOUNT_INVALID);
        // }

        if (!this.isValidOfBuyData()) {
            return; 
        }

        let available = utilGetAvailableByCoinType(this.props.balance, payCoinType);

        if (available < Number(buyAmount)) {
            return this.toast(TOAST_MESSAGE.NOT_AVAILABLE);
        }

        console.log('targetCoinType, payCoinType, buyAmount, buyPrice', buyAmount, buyPrice);

        request(API_MAP.buy, {
            method: 'post',
            data: {
                coinType,
                amount: Number(buyAmount),
                price: Number(buyPrice),
            }
        }, false, (err, res) => {
            if (err) {
                return this.toast(TOAST_MESSAGE.FAILED);
            }
            if (res.retCode == '00') {
                this.reloadUserBalanceData();
                this.setState({buyPrice:'', buyAmount: '', buyTotal: 0, buyPriceAmountTo: 0, buySliderValue: 0});
                return this.toast(TOAST_MESSAGE.SUCCESS);
            }
            return this.toast(res.retMsg || TOAST_MESSAGE.FAILED);
        }).catch(e => {
            console.info(e);
            this.toast(TOAST_MESSAGE.FAILED);
        });
    };

    checkDataInvalid = (data, validArr) => {
        for (let i = 0; i < validArr.length; i++) {
            let valid = validArr[i];
            if (!data[valid] || data[valid] == null || data[valid] == undefined) {
                return true;
            }
        }
        return false;
    };

    reloadUserBalanceData = () => {
        request(API_MAP.balance, {
            method: 'post',
            data: {bankName: 'exchange1'}
        }, false, (err, res) => {
            if (err) {
                return null;
            }
            if (res && res.data) {
                try {
                    this.props.updateExchangeBalanceInfo(res.data);
                } catch (e) {
                    // Notification.error(e);
                    this.toast(TOAST_MESSAGE.SYSTEM_ERROR)
                }
            }
        })
    }

    handleSell = () => {

        const {sellAmount, sellPrice, coinType , targetCoinType} = this.state;

        if (!utilValidCheck(sellAmount, 'amount')) {
            return this.toast(TOAST_MESSAGE.AMOUNT_INVALID);
        }

        if (!utilValidCheck(sellPrice, 'price')) {
            return this.toast(TOAST_MESSAGE.PRICE_INVALID);
        }

        if (!this.isValidOfSellData()) {
            return;
        }

        let available = utilGetAvailableByCoinType(this.props.balance, targetCoinType);
        console.info('avaliabel....', available, sellAmount);
        if (available < Number(sellAmount)) {
            return this.toast(TOAST_MESSAGE.NOT_AVAILABLE);
        }

        console.log('targetCoinType, payCoinType, buyAmount, buyPrice', sellAmount, sellPrice);

        request(API_MAP.sell, {
            method: 'post',
            data: {
                coinType,
                amount: Number(sellAmount),
                price: Number(sellPrice),
            }
        }, false, (err, res) => {
            if (err) {
                return this.toast(TOAST_MESSAGE.FAILED);
            }
            if (res.retCode == '00') {
                this.reloadUserBalanceData();
                this.setState({sellPrice: '', sellAmount: '', sellTotal: 0, sellPriceAmountTo: 0, sellSliderValue: 0});
                return this.toast(TOAST_MESSAGE.SUCCESS);
            }
            return this.toast(TOAST_MESSAGE.FAILED);
        }).catch(e => {
            this.toast(TOAST_MESSAGE.SYSTEM_ERROR);
        })
    };

    /**
     * start onChange Event
     * @todo  当前的数据计算 抽象到一个函数内
     * --------------------------------------------------------------------------
     */
    onChangeBuyPrice = (buyPrice) => {
        // console.log('?????', buyPrice);
        buyPrice = utilTransferInputValue(buyPrice, 'price');
        console.log('utilTransferInputValue', buyPrice);
        let { buyAmount, payCoinType} = this.state;
        let buyTotal = 0;
        if (buyAmount) {
            buyTotal = Number(buyPrice) * Number(buyAmount);
        }
        let amountTo = utilGetAmountToByCoinType(this.props.marketInfo, payCoinType);
        let buyPriceAmountTo = Number((buyPrice * amountTo).toFixed(4));
        this.setState({ buyPrice, buyPriceAmountTo, buyTotal });
        return buyPrice;
    }

    onChangeBuyAmount = (buyAmount) => {
        buyAmount = utilTransferInputValue(buyAmount, 'amount');
        let { buyPrice } = this.state;
        let buyTotal = 0;
        if (buyPrice) {
            buyTotal = Number(buyPrice) * buyAmount;
        }
        this.setState({ buyAmount, buyTotal });
        return buyAmount;
    }

    onChangeSellPrice = (sellPrice) => {
        sellPrice = utilTransferInputValue(sellPrice, 'price');
        console.log('onChangeSellPrice...', sellPrice);
        let { sellAmount, payCoinType } = this.state;
        let sellTotal = 0;
        if (sellAmount) {
            sellTotal = Number(sellPrice) * Number(sellAmount);
        }
        let amountTo = utilGetAmountToByCoinType(this.props.marketInfo, payCoinType)
        let sellPriceAmountTo = Number((sellPrice * amountTo).toFixed(4));
        this.setState({ sellPrice, sellPriceAmountTo, sellTotal });
        return sellPrice;
    }

    onChangeSellAmount = (sellAmount) => {
        sellAmount = utilTransferInputValue(sellAmount, 'price');
        console.log('onChangeSellAmount', sellAmount);
        let { sellPrice } = this.state;
        let sellTotal = 0;
        if (sellPrice) {
            sellTotal = Number(sellPrice) * sellAmount;
        }
        this.setState({ sellAmount, sellTotal });
        return sellAmount;
    }

    onChangeBuySlider = (type: string, value: number) => {
        let {coinType, buyPrice} = this.state;
        coinType = coinType.split('/')[1]; // || 'BTC';
        let available = utilGetAvailableByCoinType(this.props.balance, coinType);
        let buyAmount = ((available / Number(buyPrice) * value) / 100).toFixed(4);
        this.onChangeBuyAmount(buyAmount);
        this.setState({ buySliderValue: value });
    }

    onChangeSellSlider = (type: string, value: number) => {
        
        let {coinType} = this.state;
        coinType = coinType.split('/')[0]; // || 'ETH';
        let available = utilGetAvailableByCoinType(this.props.balance, coinType);

        let sellAmount = ((available * value) / 100).toFixed(4);

        this.onChangeSellAmount(sellAmount);
        this.setState({ sellSliderValue: value });
    }

    /**
     * -----------------------------    end     onchange   event    -------------------------------------------
     */
    turnToPage = (pageName: string, params?: Object) => {
        this.props.navigation.navigate(pageName, params);
    };

    /***
     * render function
     * -------------------------------------------------------------------
     */


    /**
     * the left Area for user operate
     */
    renderOptionArea = (type: string) => {
        if (type === 'buy') {
            return this.renderBuyOptionArea();
        } else if (type === 'sell') {
            return this.renderSellOptionArea();
        }
    };

    renderBuyOptionArea = () => {
        let { targetCoinType, payCoinType } = this.state;
        let coinType = this.state.payCoinType;
        let available = utilGetAvailableByCoinType(this.props.balance, coinType);
        let isLogin = utilUserIsLogin(this.props.user);

        return (
            <TransactionLeftArea
                nav={this.props.navigation}
                type={'buy'}
                targetCoinTypeText={payCoinType}
                payCoinTypeText={targetCoinType}
                available={available}
                pricePlaceholder={'买入价'}
                amountPlaceholder={'买入量'}
                onChangeSlider={this.onChangeBuySlider}
                sliderValue={this.state.buySliderValue}
                isLogin={isLogin}
                availableTitle={payCoinType}
                onAmountChange={this.onChangeBuyAmount}
                onPriceChange={this.onChangeBuyPrice}
                priceValue={this.state.buyPrice}
                amountValue={this.state.buyAmount}
                priceAmountTo={this.state.buyPriceAmountTo}
                priceTotal={this.state.buyTotal}
                handleBuy={this.handleBuy}
            >
            </TransactionLeftArea>
        )
    }

    renderSellOptionArea = () => {
        let { targetCoinType, payCoinType } = this.state;
        let coinType = this.state.targetCoinType;
        let available = utilGetAvailableByCoinType(this.props.balance, coinType);
        let isLogin = utilUserIsLogin(this.props.user);

        return (
            <TransactionLeftArea
                nav={this.props.navigation}
                type={'sell'}
                targetCoinTypeText={payCoinType}
                payCoinTypeText={targetCoinType}
                available={available}
                pricePlaceholder={'卖出价'}
                amountPlaceholder={'卖出量'}
                onChangeSlider={this.onChangeSellSlider}
                sliderValue={this.state.sellSliderValue}
                isLogin={isLogin}
                availableTitle={targetCoinType}
                onAmountChange={this.onChangeSellAmount}
                onPriceChange={this.onChangeSellPrice}
                priceValue={this.state.sellPrice}
                amountValue={this.state.sellAmount}
                priceAmountTo={this.state.sellPriceAmountTo}
                priceTotal={this.state.sellTotal}
                handleSell={this.handleSell}
            >
            </TransactionLeftArea>
        )
    }

    updateCoinSelectViewState = () => {
        let { modalVisible } = this.state;
        console.log('updateCoinSelectViewState', modalVisible);
        if (modalVisible) {
            this.setState({ modalVisible: false });
            // Animated.timing(this.state.fadeAnim, { toValue: -deviceWidth, duration: 500, }).start();
        } else {
            this.setState({ modalVisible: true });
            Animated.timing(this.state.fadeAnim, { toValue: 0, duration: 500 }).start();
        }
    }

    /**
     * renderBtn
     */
    renderBtn = (type: string) => {
        let btnText = type === 'buy' ? '买入' : '卖出';
        let btnStyle = type === 'buy' ? 'btnBuy' : 'btnSell';
        let btnFunction = type === 'buy' ? 'handleBuy' : 'handleSell';
        let { username = 'user' } = this.state;
        username = '3111';
        if (username) {
            return (
                <NccButton text={btnText} buttonStyle={styles[btnStyle]} onPress={() => {
                    this[btnFunction] && this[btnFunction]();
                }} />
            )
        }
        return (
            <NccButton text={'登录'} buttonStyle={styles[btnStyle]} onPress={() => {
                this.turnToPage(ROUTERMAP.login);
            }} />
        )
    };

    /**
     * the right area, topOrder data table
     */
    renderTopOrderData = () => {
        let { topOrderData , coinType, lastPrice } = this.state;
        let {marketInfo} = this.props;
        // console.log('render')/
        
        topOrderData = topOrderData[coinType] || {};

        let { bids : buyTop = DEFAULT_ORDER_TOP, asks: sellTop = DEFAULT_ORDER_TOP } = topOrderData;
        // let lastPrice = utilGetLastPrice(marketInfo, coinType);  // 暂时从 state 中拿
        let amountTo = utilGetAmountToByCoinType(marketInfo, coinType);

        // console.log('length...', buyTop.length, sellTop.length);
        // if (buyTop.length < 6) {
        //     for(let i = 0; i < 6 - buyTop.length; i ++) {
        //         buyTop.push({price: 0, amount: 0});
        //     }
        // }

        // if (sellTop.length < 6) {
        //     for(let i = 0; i < 6 - sellTop.length; i ++) {
        //         sellTop.push({price: 0, amount: 0});
        //     }
        // }

        return (
            <View>
                <View style={{ display: 'flex', flexDirection: 'row', marginBottom: scaleSize(11) }}>
                    <Text style={styles.topOrderTitleIndex}>盘口</Text>
                    <Text style={styles.topOrderTitlePrice}>价格</Text>
                    <Text style={styles.topOrderTitleAmount}>数量</Text>
                </View>
                {
                    this.renderTopOrderTable('sell', sellTop)
                }
                <View style={{
                    marginTop: scaleSize(2),
                    marginBottom: scaleSize(17)
                }}>
                    <Text style={{
                        fontFamily: 'Helvetica-Bold',
                        fontSize: scaleFontSize(16),
                        color: '#F25973',
                        letterSpacing: 1,
                        lineHeight: scaleSize(19)
                    }}>{lastPrice}</Text>
                    <Text style={{
                        marginTop: scaleSize(3),
                        fontFamily: 'Helvetica',
                        fontSize: scaleFontSize(10),
                        color: '#9B9B9B',
                        lineHeight: scaleSize(12),
                    }}>{`≈ ${amountTo} CNY`}</Text>
                </View>
                {
                    this.renderTopOrderTable('buy', buyTop)
                }
            </View>
        )
    }

    /**
     * 
     */
    renderTopOrderTable = (type: string, data: Array<{amount: number, price: number}>) => {
        let buyIndex = 1;
        let sellIndex = 6;
        let length = data.length;
        if (length < 6) {
            for(let i = 0; i < 6 - length; i ++) {
                data.push({amount: 0, price: 0});
            }
        }
        data = data.slice(0, 6);
        if (type === 'sell') {
            data = data.sort((a, b) => {
                return a.price - b.price;
            })
        }
        return (
            <View style={{}}>
                {
                    data.map((v, index) => {
                        return (
                            <View key={`buytable-${index}`} style={styles.topOrderTableLine}>
                                {
                                    type === 'buy' ? <Text style={styles.topOrderTableIndex}>{buyIndex ++}</Text> : <Text style={styles.topOrderTableIndex}>{sellIndex--}</Text>
                                }
                                {
                                    type === 'buy' ? (
                                        <Text style={styles.topOrderTableBuy}>{Number(v.price).toFixed(4)}</Text>
                                    ) :
                                        (<Text style={styles.topOrderTableSell}>{Number(v.price).toFixed(4)}</Text>)
                                }
                                <Text style={styles.topOrderTableAmount}>{Number(v.amount).toFixed(3)}</Text>
                            </View>
                        )
                    })
                }
            </View>
        )
    }

    renderTopBtnGroup = () => {
        const { nowTab } = this.state;
        let buyTabExtendStyle = {};
        let sellTabExtendStyle = {};
        let buyTabTextExtendStyle = {};
        let sellTabTextExtendStyle = {};

        if (nowTab === 'buy') {
            buyTabExtendStyle = {};
            sellTabExtendStyle = { backgroundColor: '#FFFFFF', borderWidth: 1, borderColor: '#ECECEC' };
            buyTabTextExtendStyle = {};
            sellTabTextExtendStyle = { color: '#C6C6C6' };
        } else {
            buyTabExtendStyle = { backgroundColor: '#FFFFFF', borderColor: '#ECECEC', borderWidth: 1 };
            sellTabExtendStyle = {};
            buyTabTextExtendStyle = { color: '#C6C6C6' };
            sellTabTextExtendStyle = {};
        }

        return (
            <View style={styles.btnGroup}>
                <NccButton text={'买入'} buttonStyle={[styles.opBtnBuy, buyTabExtendStyle]} textStyle={[styles.opBtnBuyText, buyTabTextExtendStyle]} onPress={() => {
                    this.setState({ nowTab: 'buy' })
                }} />
                <NccButton text={"卖出"} buttonStyle={[styles.opBtnSell, sellTabExtendStyle]} textStyle={[styles.opBtnSellText, sellTabTextExtendStyle]} onPress={() => {
                    this.setState({ nowTab: 'sell' })
                }} />
            </View>
        )

    }

    coinTypeSelect = (_, coinType) => {
        console.log('coinType....', coinType);
        this.updateCoinSelectViewState();
        // if (payType == 'Favorites') {
        const [targetCoinType, payCoinType] = coinType.split('/');
        // }
        this.setState({coinType: coinType, payCoinType: payCoinType, targetCoinType: targetCoinType, modalVisible: false, fadeAnim: new Animated.Value(-deviceWidth) });
    }

    /**
     * 
     * render function end
     * -------------------------------------------------------------------
     */

    render() {
        let { coinType } = this.state;
        let marketInfo = this.props.marketInfo;
        return (
            <View style={[styles.container]}>
                <CommonTitleBar title={
                    <View style={{
                        display: 'flex',
                        flexDirection: 'row',
                        height: scaleSize(20),
                    }}>
                        <Image source={icons.arrow} style={{
                            height: scaleSize(8),
                            width: scaleSize(8),
                            alignSelf: 'center',
                        }} />
                        <Text style={{
                            height: scaleSize(20),
                            lineHeight: scaleSize(20),
                            fontFamily: 'PingFangSC-Semibold',
                            fontSize: scaleSize(14),
                            color: '#4A4A4A',
                            marginLeft: scaleSize(7),
                        }}>{coinType}</Text>
                    </View>
                } nav={null} back={false} backgroundColor={'white'} textOnPress={this.updateCoinSelectViewState} />

                <Modal
                    visible={this.state.modalVisible}
                    animationType={"none"}
                    transparent={true}>
                    <TouchableOpacity activeOpacity={1} style={{ flex: 1, marginTop: 20, backgroundColor: 'rgba(0, 0, 0, 0.5)' }} onPress={() => {
                        // this.updateCoinSelectViewState();
                        this.setState({ fadeAnim: new Animated.Value(-deviceWidth), modalVisible: false });
                    }}>
                        <Animated.View style={[{
                            marginLeft: this.state.fadeAnim,
                            height: deviceHeight,
                            width: deviceWidth - 100,
                        }]}>
                            <View style={{
                                backgroundColor: '#FFFFFF',
                            }}>
                                <View style={{
                                    height: Global.titleBarHeight,
                                    marginLeft: scaleSize(20),
                                    justifyContent: 'center',
                                }}>
                                    <View style={{
                                        display: 'flex',
                                        flexDirection: 'row',
                                        height: scaleSize(20),
                                    }}>
                                        <Image source={icons.arrowLeft} style={{
                                            height: scaleSize(8),
                                            width: scaleSize(8),
                                            alignSelf: 'center',
                                        }} />
                                        <Text style={{
                                            height: scaleSize(20),
                                            lineHeight: scaleSize(20),
                                            fontFamily: 'PingFangSC-Semibold',
                                            fontSize: scaleSize(14),
                                            color: '#4A4A4A',
                                            marginLeft: scaleSize(7),
                                        }}>{coinType}</Text>
                                    </View>

                                </View>
                                <CoinTypeSelect onPress={this.coinTypeSelect} marketInfo={marketInfo} />
                            </View>
                            {/* <CoinTypeSelect onPress={this.coinTypeSelect} data={marketInfo} visiable={visiable}/> */}
                        </Animated.View>
                    </TouchableOpacity>
                </Modal>

                <ScrollView style={styles.scrollerContainer}>
                    <View style={{
                        paddingLeft: scaleSize(20),
                        paddingRight: scaleSize(20),
                        marginBottom: scaleSize(24),
                    }}>
                        <View style={styles.mainContent}>
                            <View style={styles.left}>
                                {/* <View style={styles.btnGroup}>
                                    <NccButton text={'买入'} buttonStyle={[styles.opBtnBuy]} textStyle={styles.opBtnBuyText} onPress={() => {
                                        this.setState({ nowTab: 'buy' })
                                    }} />
                                    <NccButton text={"卖出"} buttonStyle={styles.opBtnSell} textStyle={styles.opBtnSellText} onPress={() => {
                                        this.setState({ nowTab: 'sell' })
                                    }} />
                                </View> */}
                                {
                                    this.renderTopBtnGroup()
                                }
                                {
                                    this.renderOptionArea(this.state.nowTab)
                                }
                            </View>

                            <View style={styles.right}>
                                {
                                    this.renderTopOrderData()
                                }
                            </View>
                        </View>

                    </View>

                    {
                        /** line */
                        <View style={{ backgroundColor: 'rgba(236,236,236,1)', height: scaleSize(3) }}></View>
                    }

                    {
                        /**委托列表 */
                        <EntrustList data={
                            this.state.orderData
                        } cancelOrder={this.handleCancel}/>
                    }

                </ScrollView>
                {
                    /**
                     *  style={{
                            width: '80%',
                            height: 100,
                        }}
                     */
                }
                <Toast ref='toast' position={'center'} />
            </View>
        )
    }

}

export default connect(
    (state) => ({
        balance: state.exchangeBalance,
        user: state.user,
        marketInfo: state.market,
        lastPrice: state.lastPrice,
    }),
    (dispatch) => ({
        // updateBalanceInfo: (data) => dispatch(balanceAction.updateBalanceInfo(data)),
        insertLastPrice: (coinType, lastPrice) => dispatch(insertLastPrice(coinType, lastPrice)),
        updateExchangeBalanceInfo: (data) => dispatch(exchangeBalanceAction.updateBalanceInfo(data)),
    })
)(Transaction);

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column',
        backgroundColor: '#FFFFFF'
    },
    scrollerContainer: {
        // padding: scaleSize(20)
    },
    topBar: {
        height: 50
    },
    mainContent: {
        display: 'flex',
        flexDirection: 'row'
    },
    availablelArea: {
        marginTop: scaleSize(18.5)
    },
    availableTitle: {
        fontFamily: 'PingFangSC-Regular',
        height: scaleSize(17),
        fontSize: scaleFontSize(12),
        color: '#888888',
        lineHeight: scaleSize(17)
    },
    availableAmount: {
        marginTop: scaleSize(6),
        height: scaleSize(19),
        fontSize: scaleFontSize(16),
        fontFamily: 'Helvetica',
        color: '#4A4A4A'
    },
    availabelAreaExtratBtn: {
        marginTop: scaleSize(11),
        height: scaleSize(32),
        backgroundColor: Global.sellColor,
        borderRadius: 1
    },
    availabelAreaExtratText: {
        fontFamily: 'PingFangSC-Semibold',
        fontSize: scaleFontSize(16),
        color: '#FFFFFF'
    },
    btnGroup: {
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-around'
    },
    opBtnBuy: {
        flex: 1,
        borderColor: Global.buyColor,
        borderBottomWidth: 1,
        // color: Global.buyColor,
        // 
        backgroundColor: '#ECECEC'
    },
    opBtnBuyText: {
        color: Global.buyColor
    },
    opBtnSell: {
        flex: 1,
        borderBottomWidth: 1,
        borderColor: Global.sellColor,
        // color: Global.sellColor,
        backgroundColor: '#ECECEC'
    },
    opBtnSellText: {
        color: Global.sellColor
    },
    op1: {
        marginTop: scaleSize(24),
        display: 'flex',
        flexDirection: 'row'
    },
    priceInput: {
        height: scaleSize(40),
        borderColor: '#C5C5C5',
        borderWidth: 1,
        width: scaleSize(160)
    },
    amountToText: {
        marginTop: scaleSize(7),
        fontFamily: 'Helvetica',
        fontSize: scaleFontSize(10),
        color: '#9B9B9B'
    },
    btnSubtract: {
        width: 40,
        backgroundColor: '#8d8d8d',

    },
    btnPlus: {
        width: 40,
        backgroundColor: '#8d8d8d',
    },
    btnBuy: {
        backgroundColor: Global.buyColor,
    },
    btnSell: {
        backgroundColor: Global.sellColor
    },
    left: {
        width: scaleSize(160),
    },
    right: {
        width: scaleSize(137),
        marginLeft: scaleSize(41),
        // borderColor: Global.sellColor,
        // borderWidth: 2
    },
    /////
    ///// topOrderArea
    ////
    topOrderTitleIndex: {
        fontFamily: 'PingFangSC-Regular',
        fontSize: scaleFontSize(10),
        color: '#9B9B9B',
        width: scaleSize(25),
        lineHeight: scaleSize(14),
        marginBottom: scaleSize(11),
        // textAlign: ''
    },
    topOrderTitlePrice: {
        width: scaleSize(64),
        fontFamily: 'PingFangSC-Regular',
        fontSize: scaleFontSize(10),
        color: '#9B9B9B',
        textAlign: 'right',
        lineHeight: scaleSize(14),
        marginBottom: scaleSize(11),
    },
    topOrderTitleAmount: {
        width: scaleSize(47),
        fontFamily: 'PingFangSC-Regular',
        fontSize: scaleFontSize(10),
        color: '#9B9B9B',
        textAlign: 'right',
        lineHeight: scaleSize(14),
        marginBottom: scaleSize(11),
    },

    // topOrderTable
    topOrderTableLine: {
        display: 'flex',
        flexDirection: 'row',
        height: scaleSize(24),
    },
    topOrderTableIndex: {
        width: scaleSize(25),
        paddingLeft: 2,
        fontFamily: 'Helvetica',
        fontSize: scaleSize(12),
        color: '#9B9B9B',
        lineHeight: scaleSize(12)
    },
    topOrderTableBuy: {
        width: scaleSize(64),
        color: Global.buyColor,
        textAlign: 'right',
        fontFamily: 'Helvetica',
        fontSize: scaleSize(12),
        lineHeight: scaleSize(12)
    },
    topOrderTableSell: {
        width: scaleSize(64),
        color: Global.sellColor,
        textAlign: 'right',
        fontFamily: 'Helvetica',
        fontSize: scaleSize(12),
        lineHeight: scaleSize(12)
    },
    topOrderTableAmount: {
        width: scaleSize(47),
        textAlign: 'right',
        paddingLeft: 2,
        fontFamily: 'Helvetica',
        fontSize: scaleSize(12),
        color: '#9B9B9B',
        lineHeight: scaleSize(12)
    }
});




